var util={
		el:{
			success:function(title,callback){
				new PNotify({
	                title: '操作提示',
	                text: title,
	                type: 'success',
	                styling: 'bootstrap3'
	            });
				if(callback){
					setTimeout(function(){
						callback();
					},3);
				}
			},
			successAndReload:function(title){
				this.success(title, function() {
					location.reload();
				});
			},
			error:function(title,msg){
				new PNotify({
	                title: '操作提示',
	                text: msg||title,
	                type: 'error',
	                styling: 'bootstrap3'
	            });
			},
			confirm:function(title,callback){
				$("#js-modal-dialog .modal-body").html(title);
				$("#js-btn-modal-dialog").click();
				//确认
				$("#js-modal-dialog .confirm-ok").one("click",function(){
					if(callback){
						callback();
						//关闭
						$("#js-modal-dialog").click();
					}	
				});
			},
			//将原页面表单数据和本页选择的数据提交回原页面
			postBack:function (selectedItems) {
                var reg=/(\w+)=([^&]+)/g;
                var params=decodeURIComponent($("#jsFormSummery").val());
                var mc;
                var hds="";
                var items={};
                //获取本页面选择的数据合并到原页面表单数据中
				for(var p in selectedItems){
                    items[p]=selectedItems[p];
				}
                //取得原页面表单数据
                while(mc=reg.exec(params)){
				    if(!items[mc[1]]){
				        //若和选择有相同的数据项则使用选择的
                        items[mc[1]]=mc[2];
                    }
                }
                //标识为提交返回页面
                items["_isPostBack"]="1";
                //生成表单元素提交
                for(var p in items){
                    hds+=util.str.fmt('<input type="hidden" name="{0}" value="{1}"/>',p,items[p]);
				}
				var backUrl=navManage.popAndGetBack();
                $('<form method="post" action="'+backUrl+'"></form>').
                append(hds).submit();
            }
		},
		str:{
			//格式化输出fmt("{0}xxx{1}xxx",1,2)=>1xxx2xxx
			fmt:function(str,data){
				if(!str){
					return str;
				}
				//数据为数组时，转为多参数调用
				if(data instanceof Array){
					data.unshift(str);
					return arguments.callee.apply(this,data);
				}
				for(var i=1; i<arguments.length; i++){
					str=str.replace(new RegExp("\\{"+(i-1)+"\\}","gi"),arguments[i]);
				}
				return str;
			}
		},
		rootUrl:function(){
			var path="/"+webContextName+"/";
			path=path.replace(/\/+/g,"/")
			return location.protocol+"//"+location.host+path;
		},
		//获取所有请求参数
		request:{
			param:function(name){
				if(typeof name == "undefined"){
					var result = location.search.match(new RegExp("[\?\&][^\?\&]+=[^\?\&]+","g")); 
				     if(result == null){
				     	return "";
				     }
				     var params={};
				     var key="";
				     var keyVal="";
				     for(var i = 0; i < result.length; i++){
				    	 keyVal=result[i].split("=");
				    	 key=keyVal[0].substring(1);
				    	 params[key]=keyVal[1];
				     }
				     return params;
				}else{
					this.param()[name]||"";
				}
			},
			path:function(){
				return location.origin+pathname;
			},
			urlAppend:function(url,param){
				if(url){
					if(typeof param != "string"){
						param=$.param(param);
					}
					return url+(url.indexOf("?")>0?"":"?")+"&"+param;
				}
				return url;
			},
			append:function(param){
				return this.urlAppend(location.href, param);
			}
		}
}

//管理前进后退
~function () {
	var mapStr="__urlMap";
	var stackStr="__urlStack";
	var urlMap=JSON.parse(sessionStorage[mapStr]||"{}");
	var urlStack=JSON.parse(sessionStorage[stackStr]||"[]");
	var currPos=0;
    var navManage={
    	//将当前url入栈
    	push:function (url) {
            var url=url||location.href;
    		//当前位置
    		currPos=urlMap[url]||0;
    		if(!currPos){
    		    //未找到相同的url
                for(var p in urlMap){
                    var url1=p.replace(/\?.*/g,"");
                    var url2=url.replace(/\?.*/g,"");
                    if(url1==url2){
                        //找到相似的url
                        currPos=urlMap[p]||0;
                        break;
                    }
                }
            }
            //url栈里有值则不用入栈
            if(currPos){
            	return;
			}
            urlStack.push(url);
            urlMap[url]=urlStack.length;
            currPos=urlStack.length;
            //存储到session中
            this.store();
        },
        //出栈当前url
        pop:function (url) {
    	    var url=url || location.href;
            urlStack.pop(url);
            delete urlMap[url];
            //存储到session中
            this.store();
        },
        //获取回退的url
        getBack:function (count) {
    		var count=count||1;
            //定位当前位置
            for(var p in urlMap){
                if(p==location.href){
                    currPos=urlMap[p]||1;
                    break;
                }
            }
            count=count>currPos?1:count;
            //回退到的目的url
            var targetUrl=urlStack[currPos-count-1];
            return targetUrl;
        },
		//出栈并获取回退url
		popAndGetBack:function(count){
            //获取回退的url
            var targetUrl=this.getBack(count)
            //出栈当前url
            this.pop();
            return targetUrl;
		},
		//回退count次
		back:function (count) {
    		//获取回退的url
            var targetUrl=this.popAndGetBack(count);
            location.href=targetUrl;
        },
        store:function () {
            //存储到session中
            sessionStorage[mapStr]=JSON.stringify(urlMap);
            sessionStorage[stackStr]=JSON.stringify(urlStack);
        },
        //清除导航栈
        clear:function () {
            sessionStorage.removeItem(mapStr);
            sessionStorage.removeItem(stackStr);
        }
	};
	window.navManage=navManage;
}();
//入栈当前url
navManage.push();

//========================================================
$(function(){
	//菜单
	$("#js-side-menu li>a").each(function(){
		var link=$(this).attr("href") || "";
		link=link.replace(/\?.*/g,"");
		//选中当前页面菜单
		if(
            (link && location.href.indexOf(link)>=0) ||
                //选中页面所属模块菜单
            (link && location.href.substr(0,location.href.lastIndexOf("/")).indexOf(link.substr(0,link.lastIndexOf("/")))>=0)
        ){
			$(this).parent().addClass("active");
			var childMenu=$(this).closest(".child_menu").slideDown();
			childMenu.parent().addClass("active");
			return;
		}
	}).click(function () {
	    //清空导航
        navManage.clear();
    });

	//选中展开一级菜单
	//$(".child_menu",$("#js-side-menu >li[model="+_pageModel+"]").addClass("active")).show();

	//设置下拉列表选中项
	$("select[value]").each(function(){
		$("option[value='"+$(this).attr("value")+"']",this).prop("selected",true);
	});
	
	//设置单选/多选按钮选中
	$(":radio,:checkbox").each(function(){
		var _this=$(this);
		_this.prop("checked",_this.attr("check")==_this.val());
	});
	
	//设置文本框只读
	$("input[read='true']").prop("readonly",true);
	
	//日期选择器
	$('.input-date-picker').daterangepicker({
		singleDatePicker: true,
		calender_style: "picker_3",
		format: "YYYY-MM-DD",
		locale : {  
            applyLabel : '确定',  
            cancelLabel : '取消',  
            fromLabel : '起始时间',  
            toLabel : '结束时间',  
            customRangeLabel : '自定义',  
            daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],  
            monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月',  
                    '七月', '八月', '九月', '十月', '十一月', '十二月' ],  
            firstDay : 1  
        }  
   }).prop("readonly",true);
	
	//图片上传
	$(".uploader-img").dropzone({
        url: util.rootUrl()+"/sys/file/uploadProductImg.json",
        maxFiles: 1,
        maxFilesize: 1024*5,
        addRemoveLinks: true,
        dictDefaultMessage: "选择或拖动图片到此上传",
        dictFallbackMessage: "您的浏览器不支持拖动上传",
        dictInvalidFileType: "不允许上传此类型文件",
        dictFileTooBig: "文件超过大小限制",
        dictResponseError: "服务器响应错误：{{statusCode}}",
        dictCancelUpload: "取消",
        dictCancelUploadConfirmation: "确定取消上传？",
        dictMaxFilesExceeded: "只能上传1个文件",
        dictRemoveFile: "取消",
        acceptedFiles: ".jpg,.jpeg,.png,.gif",
        init: function() {
            this.on("success", function(file,result) {
            	if(result && result.result){
                	$(this.element).prev().val(result.data);
            	}
            });
        }
    });
	
	//分页
	if(window["recordTotal"] || window["pageSize"]){
		//总页数
		var totalPage=parseInt(recordTotal/pageSize,10)+(recordTotal%pageSize?1:0);
		//显示开始记录
		var recordFrom=(currPage-1)*pageSize +1;
		recordFrom=recordFrom<=0?1:recordFrom;
		//显示结束记录
		var recordTo=parseInt(recordFrom)+parseInt(pageSize) -1;
		recordTo=recordTo>recordTotal?recordTotal:recordTo;
		
		if(currPage>totalPage){
			recordFrom=0;
			recordTo=0;
			currPage=1;
		}
		
		$("#span-paging-info-from").text(recordFrom);
		$("#span-paging-info-to").text(recordTo);
		$("#span-paging-info-total").text(recordTotal);
		
		$(".table-pagination-bar").pagination({
		  total_pages: totalPage,
		  current_page: currPage,
		  prev: "上一页",
		  next: "下一页",
		  callback: function(event, page) {
			  $("form .js-paging-page").val(page);
			  $("form .js-paging-pagesize").val(pageSize);
			  $("form").submit();
			  return false;
		  }
		});
		$("form")
		.append('<input type="hidden" class="js-paging-page" name="page" value="'+currPage+'"/>')
		.append('<input type="hidden" class="js-paging-pagesize" name="pageSize" value="'+pageSize+'"/>');
	}else{
		$(".table-pagination-info").hide();
	}
	
	/*工具栏*/
	$("#div_list_toolbar a").click(function(){
		var operate=$(this).text();
		var url=$(this).attr("href");
		//需要传参数

		var needParam=/\{\d\}/.test(url);
		var recordId=$(".td_row_id :checkbox:checked").val()
		if(recordId){
			recordId=recordId.split(",");
		}else{
			recordId=[];
		}
		
		if(needParam && recordId.length==0){
			util.el.error("请选择要"+operate+"的记录！");
			return false;
		}
		
		url=util.str.fmt(url, recordId);
		
		if(url.indexOf(".html")>0){
			//页面跳转

			location.href=url;
			return false;
		}else if(url.indexOf(".json")>0){
			//ajax

			util.el.confirm("确认要"+operate+"？",function(){
				$.post(url,function(r){
					if(r && r.result){
						util.el.successAndReload(operate+"成功！");
					}else{
						util.el.error(operate+"失败！");
					}
				});
			});
			return false;
		}
	});
	
	//===============表单操作处理
	//如果是表单提交，且不是从选择页面提交返回的，则显示提交成功提示
	if(!!window["_isFormPost"] && !window["_isPostBack"]){
		//是提交返回的
		var errorList=$("#js-form-error-list");
		if($("li",errorList).length>0){
			errorList.show();
		}else{
			//提交成功弹出提示
			util.el.success("保存");
		}
	}

	//表单页面取消并返回按钮
	$("#jsBtnCancelAndBack").click(function () {
        navManage.back(1);
        return false;
    });

	//设置单选、复选框选中样式
	$('input[checked]').iCheck("check");
	$("input:checkbox").on("ifClicked",function () {
		if($(this).attr("name")=="__recordId"){
			//数据表格中行的选择操作
			$(this).closest(".table_row").toggleClass("selected");
			return false;
		}
    });

	//错误信息显示
	// if(_isPostBack){
	// 	$("#js-form-error-list").hide();
	// }

	//列表页面表格选择
	$("table .table_row").click(function () {
		$(":checkbox[name='__recordId']",$(this).parent()).iCheck("uncheck");
		$(this).toggleClass("selected");
		if($(this).is(".selected")){
            $(this).find(":checkbox").iCheck("check");
		}
    });

	//跳转到选择页面的按钮
	$(".btn-chooser").click(function(){
		var url=$(this).attr("href");
		//将本页表单数据和当前页面地址序列化提交传到选择页面
		var param=$("input:text,input:checkbox,input:radio,input:hidden[name!='__form'],select").serialize();
		$('<form method="post" action="'+url+'"></form>').append('<input type="hidden" name="__form" value="'+param+'"/>').submit();
		return false;
	});
});

//vue组件======================================
//表单-输入框
Vue.component('f_input', {
    props: {
    	name:{
    		type: String,
			default: ''
		},
		text:{
    		type: String,
			default: ''
		},
		id:{
    		type: String,
			default: ''
		},
		type:{
    		type: String,
			default: 'text'
		},
		value:{
    		type: String,
			default: ''
		},
        placeholder:{
    		type: String,
			default: ''
		},
        readonly:{
    		type: Boolean,
			default: false
		}
	},
    template: '#template-form-row-input'
});
//表单-选择器
Vue.component('f_chooser', {
    props: {
        name:{
            type: String,
            default: ''
        },
        text:{
            type: String,
            default: ''
        },
        id:{
            type: String,
            default: ''
        },
        value:{
            type: String,
            default: ''
        },
		name2:{
        	type: String,
			default: ''
		},
		value2:{
        	type: String,
			default: ''
		},
		url:{
        	type: String,
			default: ''
		},
        placeholder:{
            type: String,
            default: ''
        },
        readonly:{
            type: Boolean,
            default: true
        }
    },
    template: '#template-form-row-chooser'
});
//表单-下拉框
Vue.component('f_select', {
    props: {
        name:{
            type: String,
            default: ''
        },
        text:{
            type: String,
            default: ''
        },
        id:{
            type: String,
            default: ''
        },
        value:{
            type: String,
            default: ''
        },
        readonly:{
            type: Boolean,
            default: false
        }
    },
    template: $('#template-form-row-select').val()
});
//表单-单选框
Vue.component('f_radio', {
    props: {
        name:{
            type: String,
            default: ''
        },
        text:{
            type: String,
            default: ''
        },
        text1:{
            type: String,
            default: ''
        },
        text2:{
            type: String,
            default: ''
        },
        value:{
            type: String,
            default: ''
        },
        value1:{
            type: String,
            default: ''
        },
        value2:{
            type: String,
            default: ''
        }
    },
    template: '#template-form-row-radio'
});

//查询页面表单组件================================
//搜索输入框
Vue.component('s_input', {
    props: {
        name:{
            type: String,
            default: ''
        },
        id:{
            type: String,
            default: ''
        },
        text:{
            type: String,
            default: ''
        },
        value:{
            type: String,
            default: ''
        },
        readonly:{
            type: Boolean,
            default: false
        }
    },
    template: '#template-search-form-col-input'
});
//搜索下拉框
Vue.component('s_select', {
    props: {
        name:{
            type: String,
            default: ''
        },
        id:{
            type: String,
            default: ''
        },
        text:{
            type: String,
            default: ''
        },
        value:{
            type: String,
            default: ''
        },
		deftext:{
        	type: String,
			default: ''
		}
    },
    template: $('#template-search-form-row-select').val()
});
//搜索选择器
Vue.component('s_chooser', {
    props: {
        name:{
            type: String,
            default: ''
        },
        text:{
            type: String,
            default: ''
        },
        id:{
            type: String,
            default: ''
        },
        value:{
            type: String,
            default: ''
        },
        name2:{
            type: String,
            default: ''
        },
        value2:{
            type: String,
            default: ''
        },
        url:{
            type: String,
            default: ''
        },
        placeholder:{
            type: String,
            default: ''
        },
        readonly:{
            type: Boolean,
            default: true
        }
    },
    template: '#template-search-form-col-chooser'
});
//搜索面板
Vue.component('s_panel', {
    template: "#template-search-panel"
});
Vue.component('s_buttons', {
	props:{
		cols:{
            type: Number,
            default: 0
        }
	},
    template: "#template-search-buttons"
});
Vue.component('s_button', {
	props:{
		type:{
			type: String,
			default: ''
		},
		id:{
			type: String,
			default: ''
		},
        icon:{
            type: String,
            default: ''
        },
        href:{
            type: String,
            default: ''
        },
		col:{
			type: Number,
			default: 0
		}
	},
    template: "#template-search-button"
});


//搜索列表页面标题
Vue.component('s_title', {
    props: {
        title:{
            type: String,
            default: '标题'
        }
    },
    template: "#template-search-title"
});

//数据表格
Vue.component('d_table', {
    props: {
        minWidth:{
            type: Number,
            default: 0
        },
        cols:{
            type: Number,
            default: 20
        }
    },
    template: $('#template-list-data-grid').val()
});
Vue.component('d_head', {
    template: '<thead><slot></slot></thead>'
});
Vue.component('d_body', {
    template: '<tbody><slot></slot></tbody>'
});
Vue.component('d_tr', {
    props: {
        cls:{
            type: String,
            default: ''
        }
    },
    template: '<tr :class="cls" role="row"><slot></slot></tr>'
});
Vue.component('d_th', {
    props: {
        cls:{
            type: String,
            default: ''
        }
    },
    template: '<th :class="cls"><slot></slot></th>'
});
Vue.component('d_td', {
    props: {
        cls:{
            type: String,
            default: ''
        }
    },
    template: '<td :class="cls"><slot></slot></td>'
});

new Vue({el: '#appRoot'});